package sortingBasic.bubbleSort;

import sortingBasic.usingComparable.Student;

/**
 * 选择排序
 * mxf
 * 2018年5月18日15:07:06
 * 像是摸牌，摸出一张挨个与后面的元素进行比较，on²级别
 */
public class SelectionSort {

    private SelectionSort(){}

    public static void sort(Comparable[] arr) {
        int length = arr.length;
        for(int i = 0; i < length; i++) {
            int minIndex = i;// 最小索引
            // 与[i+1, length)逐一进行比较
            for(int j = i + 1; j < length; j++) {
                if(arr[j].compareTo(arr[minIndex]) < 0) {
                    minIndex = j;
                }
            }
            swap(arr, i, minIndex);
        }
    }

    // 两数组元素交换位置
    public static void swap(Object[] arr , int i, int j) {
        Object t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public static void main(String[] args) {

        // 测试Integer
        System.out.println("#########################测试Integer###########################");
        Integer[] arr = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
        SelectionSort.sort(arr);
        for( int i = 0 ; i < arr.length ; i ++ ){
            System.out.print(arr[i]);
            System.out.print(' ');
        }
        System.out.println();

        // Double
        System.out.println("#########################测试Double###########################");
        Double[] arr2 = {2.3, 9.9, 8.9, 7.8, 6.3, 5.3, 4.4, 3.5, 2.2, 1.4};
        SelectionSort.sort(arr2);
        for( int i = 0 ; i < arr2.length ; i ++ ){
            System.out.print(arr2[i]);
            System.out.print(' ');
        }
        System.out.println();

        // 测试自定义类
        System.out.println("#########################测试Student###########################");
        Student[] arr3 = new Student[3];
        arr3[0] = new Student("mxf", 98);
        arr3[1] = new Student("zyn", 100);
        arr3[2] = new Student("sio", 99);
        SelectionSort.sort(arr3);
        for( int i = 0 ; i < arr3.length ; i ++ ){
            System.out.println(arr3[i].toString());
        }

    }
}
